//
//  AddNewAddressViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-10-28.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "AddNewAddressViewController.h"

@interface AddNewAddressViewController ()

@end

@implementation AddNewAddressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [mapView viewWillAppear];
    mapView.delegate = self;
    locService.delegate = self;
    searcher.delegate  = self;

    if (self.comeSuperVC){
        [locService startUserLocationService];
    }

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [mapView viewWillDisappear];
    mapView.delegate = nil;
    locService.delegate = nil;
    searcher.delegate = nil;
    _comeSuperVC = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.titleLabel.text = @"添加常用地址";
    emplTimeArray = [[NSMutableArray alloc] init];

    [self initViews];

    [self getDingWeiInfo];  //获取定位信息

}

#pragma mark
#pragma mark UI 布局
-(void)initViews
{
    mScrollView = [[UIScrollView alloc] initWithFrame:self.contentView.bounds];
    mScrollView.contentSize = CGSizeMake(320, 568-64);
    mScrollView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:mScrollView];

    mSegmentedControl = [[XSegmentedControl alloc] initWithItems:@[@"",@""]];
    // 设置为 0
    mSegmentedControl.frame = CGRectZero;
    mSegmentedControl.selectedSegmentIndex = 0;
    mSegmentedControl.tintColor = UIColorFromRGB(0xff6800);
    [mSegmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [mScrollView addSubview:mSegmentedControl];

    indexView1 = [UIView initViewRect:CGRectMake(0, height_y(mSegmentedControl),UI_SCREEN_WIDTH, self.contentView.frame.size.height-(height_y(mSegmentedControl)))  andBackGroudColor:[UIColor clearColor]];
    [mScrollView addSubview:indexView1];

// 请选择地址
    UIImageView * addressIV = [UIImageView initImageViewRect:CGRectMake(20, 15, 280, 40) andImage:LOADIMAGE(@"inputadress@2x") andUserInteractionEnabled:YES];
    [indexView1 addSubview:addressIV];
// 请选择详细地址
    UIImageView * detailAddressIV = [UIImageView initImageViewRect:CGRectMake(20, height_y(addressIV)+15, 280, 40) andImage:LOADIMAGE(@"detailaddress@2x") andUserInteractionEnabled:YES];
    [indexView1 addSubview:detailAddressIV];

    addressLB = [UILabel initLabelText:@"请选择地址" andRect:CGRectMake(61,0,200,40) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:14.5] andTextColor:UIColorFromRGB(0x666666) andTextAlignment:NSTextAlignmentLeft];
    addressLB.userInteractionEnabled = YES;
    [addressIV addSubview:addressLB];

    detailAddressTF  = [[UITextField alloc] initWithFrame:CGRectMake(61, 0, 210, 40)];
    detailAddressTF.placeholder = @"请输入详细地址";
    detailAddressTF.font  =[UIFont systemFontOfSize:14.5];
    detailAddressTF.textColor = UIColorFromRGB(0x666666);
    detailAddressTF.delegate = self;
    detailAddressTF.backgroundColor = [UIColor clearColor];
    detailAddressTF.returnKeyType = UIReturnKeyDone;
    detailAddressTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    detailAddressTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [detailAddressIV addSubview:detailAddressTF];


    // 选择地址
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseAddress)];
    [addressLB addGestureRecognizer:tap2];

// 脚 View
    UIView * footview = [UIView initViewRect:CGRectMake(0, self.view.frame.size.height-49, UI_SCREEN_WIDTH, 49) andBackGroudColor:[UIColor whiteColor]];
    [self.view addSubview:footview];

    UIView * line = [UIView initViewRect:CGRectMake(0, 0.5, UI_SCREEN_WIDTH, 0.5) andBackGroudColor:UIColorFromRGB(0xdcdcdc)];
    [footview addSubview:line];

// 脚 按钮
    UIButton * suerOrChooseBtn = [UIButton initButton:CGRectMake(45,4.5, 230, 40) btnImage:LOADIMAGE(@"xiadan@2x") btnTitle:@"确认地址" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [suerOrChooseBtn addTarget:self action:@selector(sureAddress) forControlEvents:UIControlEventTouchUpInside];
    [footview addSubview:suerOrChooseBtn];

    //百度地图
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;

    mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, height_y(detailAddressIV)+20, UI_SCREEN_WIDTH, 220)];
    [mapView setZoomLevel:17];

    [indexView1 addSubview:mapView];

    searcher = [[BMKGeoCodeSearch alloc]init];
    searcher.delegate = self;

}

#pragma mark
#pragma mark 选择地址
-(void)chooseAddress
{
    [detailAddressTF resignFirstResponder];
    ChooseAddressViewController * chooseVC = [[ChooseAddressViewController alloc] init];
    chooseVC.delegate = self;
    [self.navigationController pushViewController: chooseVC animated:YES];
}

#pragma mark
#pragma mark 确认地址 - 如果没有填写 弹出提示框
-(void)sureAddress
{

    if ([addressLB.text isEqualToString:@"请选择地址"]){
        [XDTools showTips:@"请选择地址" toView:self.view];
        return;
    }
    if (!(IS_NOT_EMPTY(detailAddressTF.text))){
        [XDTools showTips:@"请输入详细地址" toView:self.view];
        return;
    }

    [self saveAddress];


}
#pragma mark
#pragma mark  选择拍摄方式
-(void)segmentAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0){
        indexView1.hidden = NO;
        indexView2.hidden = YES;
    }else{
        indexView1.hidden = YES;
        indexView2.hidden = NO;

        if (indexView2 == nil){
            indexView2 = [UIView initViewRect:indexView1.frame andBackGroudColor:[UIColor clearColor]];
            [mScrollView addSubview:indexView2];

            UIImageView * yinpengIV = [UIImageView initImageViewRect:CGRectMake(20, 15, 280, 40) andImage:LOADIMAGE(@"inputadress@2x") andUserInteractionEnabled:YES];
            [indexView2 addSubview:yinpengIV];

            UIImageView * timeIV = [UIImageView initImageViewRect:CGRectMake(20,height_y(yinpengIV)+15, 280, 40) andImage:LOADIMAGE(@"inputtime@2x") andUserInteractionEnabled:YES];
            [indexView2 addSubview:timeIV];



            UIView * textbgView = [UIView initViewRect:CGRectMake(20, height_y(timeIV)+20, 280, 200) andBackGroudColor:[UIColor clearColor]];
            textbgView.layer.cornerRadius = 5;
            textbgView.layer.masksToBounds = YES;
            textbgView.layer.borderWidth = 1;
            textbgView.layer.borderColor =[UIColorFromRGB(0xd4ccc5) CGColor];
            [indexView2 addSubview:textbgView];

            textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 260, 180)];
            textView.font = [UIFont systemFontOfSize:14.5];
            textView.textColor = UIColorFromRGB(0x6f6254);
            textView.backgroundColor = [UIColor clearColor];
            textView.editable = NO;
            [textbgView addSubview:textView];


        }
    }
}


#pragma mark
#pragma mark UITextFiled Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark
#pragma mark ChooseAddressViewController Delegate
-(void)chooseBMKPoiInfoFromBaiDuMap:(BMKPoiInfo *)poi
{
    if (poi == nil){
        if ([addressLB.text isEqualToString:@"请选择地址"]){
            //发起反向地理编码检索
            CLLocationCoordinate2D coordinate;
            coordinate.longitude = longitude;
            coordinate.latitude = latitude;
            BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
            reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
            BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
            if(flag)
            {
                NSLog(@"反geo检索发送成功");
            }
            else
            {
                NSLog(@"反geo检索发送失败");
            }
        }
    }else{
        //        mapView.showsUserLocation =NO;

        latitude = poi.pt.latitude;
        longitude =poi.pt.longitude;

        addressLB.text = poi.name;

        mapView.delegate = self;

        NSArray* array = [NSArray arrayWithArray:mapView.annotations];
        [mapView removeAnnotations:array];

        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = poi.pt;
        item.title = poi.name;
        [mapView addAnnotation:item];

    }
}


#pragma mark
#pragma mark 定位
-(void)getDingWeiInfo
{
    if([XDTools sharedXDTools].latitude&&[XDTools sharedXDTools].longitude){
        [locService startUserLocationService];
        mapView.showsUserLocation = NO;//先关闭显示的定位图层
        mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
        mapView.showsUserLocation = YES;//显示定位图层
    }else{
        [XDTools showTips:@"请在隐私中打开定位服务" toView:self.view];
    }
}

#pragma mark
#pragma mark 地图定位+显示
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
-(void)willStartLocatingUser
{
    DDLOG(@"开始定位");
}

-(void)didStopLocatingUser
{

}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];

        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
    }

}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];

        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度

        [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];

        //发起反向地理编码检索
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
        BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    }
}


/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    DDLOG(@"error = %@",error);
}



//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        addressLB.text = result.address;
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}


#pragma mark
#pragma mark 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    DDLOG_CURRENT_METHOD;
    NSString *AnnotationViewID = @"annotationViewID";
	//根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
		((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
		((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
	annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
	annotationView.canShowCallout = YES;
    annotationView.draggable = NO;
    [self performSelector:@selector(changeCenter) withObject:self afterDelay:1.5f];
    [mapView setCenterCoordinate:annotation.coordinate animated:YES];

    return annotationView;
}

-(void)changeCenter
{
    CLLocationCoordinate2D cooreinate;
    cooreinate.latitude = latitude;
    cooreinate.longitude = longitude;
    [mapView setCenterCoordinate:cooreinate animated:YES];

}


// 返回按钮
-(void)backPrePage
{
    [locService stopUserLocationService];
    mapView.showsUserLocation = NO;
    mapView.delegate = nil;
    locService.delegate = nil;
    searcher.delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];
//    [self.navigationController dismissViewControllerAnimated:YES completion:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






// 保存地址
//必选(string) CustomerID(顾客ID); 必选(string) address(详细地址);
- (void)saveAddress{
    NSString *addressStr = [NSString stringWithFormat:@"%@%@",addressLB.text,detailAddressTF.text];
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
    NSDictionary *dic = @{@"Address": addressStr, @"CustomerID": userID};
    [self getDataWithDict:dic api:API_add_customer_address];
}
// 发送网络请求，添加地址。
-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];


        if([[tempDic objectForKey:@"status"]intValue] == 1){

            if ([api isEqualToString:API_add_customer_address]) {

                [XDTools showTips:@"添加地址成功" toView:self.contentView];
                [self performSelector:@selector(backPrePage) withObject:nil afterDelay:1.0];
                
            }else{
            }

        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.contentView];
        }

    }];

    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


@end

